<template>
  <div class="container">
    <el-row class="mb10">
      <el-col :span="16" align="left">
        <div class="flex">
          <el-input clearable v-model="searchParams.projectname" placeholder="项目名称"
            style="width: 120px; margin-right: 15px">
          </el-input>

          <el-input clearable v-model="searchParams.applicationunit" placeholder="申报单位/项目负责人"
            style="width: 180px; margin-right: 15px">
          </el-input>

          <el-select clearable v-model="searchParams.completionperiod" placeholder="完成年限">
            <el-option :label="item.itemName" :value="item.itemValue" :key="item.itemValue"
              v-for="item in options.yearList" />
          </el-select>


          <el-date-picker style="width: 233px; margin-right: 15px" v-model="data.time" type="daterange"
            range-separator="-" start-placeholder="申报开始日期" end-placeholder="申报结束日期" @change="dataPickerChange">
          </el-date-picker>

<!--
          <el-select clearable v-model="searchParams.status" placeholder="状态">
            <el-option :label="item.itemName" :value="item.itemValue" :key="item.itemValue"
              v-for="item in options.statusDate" />
          </el-select>
-->
          <el-select  v-model="data.statusUpdate" placeholder="状态">
            <el-option
                :label="item.itemName"
                :value="item.itemValue"
                :key="item.itemValue"
                v-for="item in options.statusDate"
            />
          </el-select>

          <el-button color="#626aef" @click="getListData" class="ordinary">搜索</el-button>
        </div>
      </el-col>
      <el-col :span="8" align="right">
<!--        <el-button class="ordinary" @click="getExport()" v-limit="'XMZX:KYXMLXPS:GZDGSC:EXPORT'"> 批量导出</el-button>-->
        <el-button class="ordinary" @click="handleExport()" v-limit="'KJSL:KJJL:YXKJRC:EXPERT'"> 批量导出</el-button>
        <el-button type="primary" @click="handleExamina()" v-limit="'XMZX:KYXMLXPS:GZDGSC:OUTREV'">大纲审查</el-button>
      </el-col>
    </el-row><!--  @row-dblclick="handleRowClick"-->
    <el-table :data="data.allTableData" style="width: 100%" class="center-table"
      @selection-change="handleSelectionChange"    @row-dblclick="handleRowClick"  v-loading="data.allTableloading"  >
      <el-table-column width="55" align="center" prop="checked" label="选择">
        <template #default="{ row, $index }">
          <el-checkbox v-model="row.checked" @change="selectTable($event, row, $index)"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" :index="indexMethod" width="60px"></el-table-column>
      <el-table-column label="工作大纲" type="index" width="120px">
        <template #default="{ row }">
          <span style="cursor: pointer;color: #409eff;" v-if="row.status == '已上报'||row.type != '5'||row.status == '审批不通过'"
            @click="handleDetail(row, 'look')">查看上报记录</span>
          <span style="cursor: pointer;text-decoration: underline;" v-else @click="handleDetail(row, 'edit')"
            v-limit="'XMZX:KYXMLXPS:GZDGSC:OUTREV'">上报</span>
        </template>
      </el-table-column>
      <ColumnData v-for="column of data.columns" :key="column.label" :item="column"   />
      <el-table-column label="操作" width="200" fixed="right" >
        <template #default="{ row }">
          <el-button size="small" @click="handleDetail(row, 'look')" class="ordinary"
            v-limit="'XMZX:KYXMLXPS:GZDGSC:DETAILS'">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="tc mt15">
      <el-pagination background v-model:current-page="data.page" v-model:page-size="data.pageSize"
        layout="prev, pager, next ,total,jumper" :total="data.total" :page-size="data.pageSize"
        @current-change="pageChange" />
    </div>


    <el-dialog v-model="data.detailVisible" :append-to-body="false" width="900px" @close="close"
      :show-close="false" :close-on-click-modal="false">
      <div class="my-header">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane :initData="data.initData" label="详情信息" name="first">
            <el-form label-position="top" status-icon ref="ruleFormRef" :model="data.detail" :rules="rules">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectname">
                    <el-input placeholder="请输入" :disabled="data.dialogType == 'look'" v-model="data.detail.projectname"
                      style="width: 100%"  maxlength="100" show-word-limit clearable  />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="申报单位" prop="applicationunit">

                    <el-input v-if="data.dialogType == 'look'" disabled maxlength="11" placeholder="请输入"
                      v-model="data.detail.applicationunit" style="width: 100%" />

                    <popup-tree-input v-else :data="data.orgAllList" :props="data.popupTreeProps" :prop="deptForm.parentName == null
                        ? $t('message.org.top_menu')
                        : data.detail.applicationunit
                      " :node-key="'' + deptForm.parentId" :current-change-handle="changeUnit" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="项目负责人" prop="projectleader">
                    <user-list-modal :disabled="data.dialogType == 'look'" v-model="data.detail.projectleader"
                      @update:modelValue="changeProject" :default-users="[]" :multiple="false" :devType="'platform'" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="联系电话" prop="telephone">
                    <el-input :disabled="data.dialogType == 'look'" maxlength="32" placeholder="请输入"
                      v-model="data.detail.telephone" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="完成年限" prop="completionperiod">
                    <el-select :disabled="data.dialogType == 'look'" v-model="data.detail.completionperiod"
                      placeholder="请选择" style="width: 100%">
                      <el-option :label="item.itemName" :value="item.itemValue" :key="item.itemValue"
                        v-for="item in options.yearList" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="总投资(万元)" prop="totalinvestment">
                    <el-input  :min="0" :disabled="data.dialogType == 'look'" placeholder="请输入"
                      v-model="data.detail.totalinvestment" style="width: 100%"  maxlength="16"
                              oninput="value=value.replace(/[^\d.]/g, '')
                                            .replace(/\.{2,}/g, '.').replace('.', '$#$')
                                            .replace(/\./g, '')
                                            .replace('$#$', '.')
                                            .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                                            .replace(/^\./g, '')"
                              show-word-limit  clearable />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="申请中咨拨款(万元)" prop="applyfunding">
                    <el-input  :min="0" :disabled="data.dialogType == 'look'" placeholder="请输入"
                      v-model="data.detail.applyfunding" style="width: 100%"  maxlength="16"
                               oninput="value=value.replace(/[^\d.]/g, '')
                                            .replace(/\.{2,}/g, '.').replace('.', '$#$')
                                            .replace(/\./g, '')
                                            .replace('$#$', '.')
                                            .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                                            .replace(/^\./g, '')"
                               show-word-limit  clearable />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="申报日期" prop="reporttime">
                    <el-date-picker :disabled="data.dialogType == 'look'" v-model="data.detail.reporttime"
                      placeholder="选择日期" clearable style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row> </el-row>

              <el-form-item label="主要研究内容">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.researchcontents"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="主要技术经济指标">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.mainindicators"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="创新点及可能获得的成果和知识产权">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.describetwo"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="立项背景(包括项目背景、项目概况、研究的必要性等)">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.backdrop"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="国内外研究概况及可行性分析" prop="analysis">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.analysis"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="项目研究的主要内容及技术指标(包括要解决的主要技术难点和问题，研究的创新点和内容、主要技术指标及其水平、提交的成果及形式等)">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.qualification"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="项目研究的技术路线(包括拟采取的技术路线，与后续技术改造或基本建设计划的衔接等)">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.roadmap"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="推广应用前景及经济效益预测(包括市场需求或推广应用前景、经济效益，形成的生产能力或有关节约工程造价、缩短工期指标等)">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.forecast"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="申报单位和协作单位及分工(包括项目承担单位、主要协作单位（仅限中咨集团下属单位）简介及分工等)">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.dividethework"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="项目进度计划(包括年度工作进度安排及完成期限等)(包括项目承担单位、主要协作单位（仅限中咨集团下属单位）简介及分工等)">
                <el-input :disabled="data.dialogType == 'look'" v-model="data.detail.programme"
                  :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
              </el-form-item>

            </el-form>
          </el-tab-pane>
          <el-tab-pane label="项目经费预算" name="second"  >
            <!-- <BudgettableJson :fatherTableJson="data.tableJson" :addFlag="2" @tableJson="changeBudget" /> -->
            <Budget v-if="data.detailVisible" title="详情" :initData="data.tableJson" @tableJson="changeBudget" />
          </el-tab-pane>
          <el-tab-pane label="相关附件" name="4" >
            <PlatformFilesxq :files="data.files" @filesParams="filesParams"   download="KJSL:KJCG:XSLW:DOWNLOAD"  upload="KJSL:KJCG:XSLW:UPLOAD" fileDelete="KJSL:KJCG:XSLW:FILEDELET"></PlatformFilesxq>
          </el-tab-pane>
          <el-tab-pane v-if="data.approvalFormalExamination.modifyUsername" label="审批详情" name="approvalInfo">
              <el-form class="inline-form" label-position="top" status-icon label-width="140px">
                <el-form-item label="审查结果："> {{data.approvalFormalExamination.status}} </el-form-item>
                <el-form-item label="审查人：">  {{data.approvalFormalExamination.modifyUsername}} </el-form-item>
                <el-form-item label="审查时间："> {{data.approvalFormalExamination.reviewtime}} </el-form-item>
                <el-form-item label="审查意见：">
                  <el-input type="textarea" disabled v-model="data.approvalFormalExamination.comment"></el-input>
                </el-form-item>
                <el-form-item label="附件："> 
                  <template v-if="data.approvalFormalExamination.files && data.approvalFormalExamination.files.length">
                     <div v-for="(file , i) in data.approvalFormalExamination.files" style="margin-right: 10px" :key="'fiels' + i">
                      <el-link type="primary"  :href="file.url" target="_blank">{{file.name}}</el-link>
                     </div>
                  </template>
                </el-form-item>
              </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.detailVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm()" v-if="data.dialogType == 'edit'">保存</el-button>
        </span>
      </template>
    </el-dialog>

      
    <Dialog v-if="data.examinationVisible" :dialog="data.examinationVisible" @changeDialog="changeDialog" title="大纲审查" :checkId="data.tableItem.id">
    </Dialog>

    <!--新增、修改、确认弹框-->
    <el-dialog class="global-dialog" v-model="data.dialogVisible" :lock-scroll="false" :append-to-body="false"
      width="950px" @closed="handleClose" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane :initData="data.initData" label="基本信息" name="first">
              <el-form label-position="top" :rules="rules"  :model="data.ruleForm" status-icon>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="项目名称" prop="projectname">
                      <el-input placeholder="请输入" v-model="data.ruleForm.projectname" style="width: 100%"  maxlength="100" show-word-limit clearable/>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="申报单位" prop="applicationunit">
                      <popup-tree-input :data="data.orgAllList" :props="data.popupTreeProps" :prop="deptForm.parentName == null
                          ? $t('message.org.top_menu')
                          : data.ruleForm.applicationunit
                        " :node-key="'' + deptForm.parentId" :current-change-handle="changeUnit" />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="项目负责人" prop="projectleaderid">
                      <user-list-modal v-model="data.ruleForm.projectleader" @update:modelValue="changeProject"
                        :default-users="[]" :multiple="false" :devType="'platform'" />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="联系电话" prop="telephone">
                      <el-input maxlength="32" placeholder="请输入" v-model="data.ruleForm.telephone" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="完成年限" prop="completionperiod">
                      <el-select v-model="data.ruleForm.completionperiod" placeholder="请选择" style="width: 100%">
                        <el-option :label="item.itemName" :value="item.itemValue" :key="item.itemValue"
                          v-for="item in options.yearList" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="总投资(万元)" prop="totalinvestment">
                      <el-input :min="0" placeholder="请输入" v-model="data.ruleForm.totalinvestment"
                        style="width: 100%"  maxlength="16"
                                oninput="value=value.replace(/[^\d.]/g, '')
                                            .replace(/\.{2,}/g, '.').replace('.', '$#$')
                                            .replace(/\./g, '')
                                            .replace('$#$', '.')
                                            .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                                            .replace(/^\./g, '')"
                                show-word-limit  clearable />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="申请中咨拨款(万元)" prop="applyfunding">
                      <el-input  :min="0" placeholder="请输入" v-model="data.ruleForm.applyfunding"
                        style="width: 100%"   maxlength="16"
                                 oninput="value=value.replace(/[^\d.]/g, '')
                                            .replace(/\.{2,}/g, '.').replace('.', '$#$')
                                            .replace(/\./g, '')
                                            .replace('$#$', '.')
                                            .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                                            .replace(/^\./g, '')"
                                 show-word-limit  clearable/>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="申报日期" prop="reporttime">
                      <el-date-picker v-model="data.ruleForm.reporttime" placeholder="选择日期" clearable
                        style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row> </el-row>

                <el-form-item label="主要研究内容" prop="researchcontents">
                  <el-input v-model="data.ruleForm.researchcontents" :autosize="{ minRows: 2, maxRows: 6 }"
                    type="textarea" placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="主要技术经济指标" prop="mainindicators">
                  <el-input v-model="data.ruleForm.mainindicators" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="创新点及可能获得的成果和知识产权" prop="describetwo">
                  <el-input v-model="data.ruleForm.describetwo" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="立项背景(包括项目背景、项目概况、研究的必要性等)" prop="backdrop">
                  <el-input v-model="data.ruleForm.backdrop" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入"  maxlength="2000" show-word-limit />
                </el-form-item>

                <el-form-item label="国内外研究概况及可行性分析" prop="analysis">
                  <el-input v-model="data.ruleForm.analysis" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="项目研究的主要内容及技术指标(包括要解决的主要技术难点和问题，研究的创新点和内容、主要技术指标及其水平、提交的成果及形式等)" prop="qualification">
                  <el-input v-model="data.ruleForm.qualification" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="项目研究的技术路线(包括拟采取的技术路线，与后续技术改造或基本建设计划的衔接等)" prop="roadmap">
                  <el-input v-model="data.ruleForm.roadmap" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="推广应用前景及经济效益预测(包括市场需求或推广应用前景、经济效益，形成的生产能力或有关节约工程造价、缩短工期指标等)" prop="forecast">
                  <el-input v-model="data.ruleForm.forecast" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="申报单位和协作单位及分工(包括项目承担单位、主要协作单位（仅限中咨集团下属单位）简介及分工等)" prop="dividethework">
                  <el-input v-model="data.ruleForm.dividethework" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>

                <el-form-item label="项目进度计划(包括年度工作进度安排及完成期限等)(包括项目承担单位、主要协作单位（仅限中咨集团下属单位）简介及分工等)" prop="programme">
                  <el-input v-model="data.ruleForm.programme" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请输入" maxlength="2000" show-word-limit  />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- <el-tab-pane label="项目经费预算" name="second">
              <Budget
                :fatherTableJson="data.tableJson"
                :addFlag="data.addFlag"
                @tableJson="changeBudget"
              />
            </el-tab-pane> -->
            <el-tab-pane label="项目经费预算" name="second">
              <!-- <BudgettableJson :fatherTableJson="data.tableJson" :addFlag="2" @tableJson="changeBudget" /> -->
              <Budget v-if="data.detailVisible" title="详情" :initData="data.tableJson" @tableJson="changeBudget" />
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="4">
              <PlatformFilesxq :files="data.files" @filesParams="filesParams"   download="KJSL:KJCG:XSLW:DOWNLOAD"  upload="KJSL:KJCG:XSLW:UPLOAD" fileDelete="KJSL:KJCG:XSLW:FILEDELET"></PlatformFilesxq>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.dialogVisible = false">关闭</el-button>
          <!-- <el-button type="primary" @click="submitForm()">保存</el-button> -->
        </span>
      </template>
    </el-dialog>
    <!-- 导出字段选择 -->
    <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
    ></Export>
  </div>
</template>
<script lang="ts">
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import { validatePhoneNumber } from "@/utils/util";
import { getDetailById,getApprovalById, getExportApply } from '@/views/project/api/projectApplication';
import UserListModal from "@/views/project/components/UserListModal/index.vue";
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import ColumnData from '@/views/science/components/table/column-data.vue';
import { Modals, tips } from "@/views/science/components/tips/tips";
import platformFiles from "@/views/science/technologyStrength/components/platformFiles/platformFiles.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import moment from "moment";
import { ObjectType } from "typings/interfaces";
import { onMounted, reactive, ref } from "vue";
//import Budget from "./components/budget.vue";
import Budget from "@/views/project/components/BudgetTable/budgetTable.vue";

import Dialog from "./components/dialog.vue";
import tableData from "./tableHeader.json";
import Export from '@/views/project/components/Export/index.vue'
//import BudgettableJson from "@/views/project/research-project/preliminaryExamination/budgetTable.vue";
import PlatformFiles from "@/views/project/research-project/preliminaryExamination/platformFiles/platformFiles.vue";
import PlatformFilesxq from "@/views/project/research-project/preliminaryExamination/platformFiles/platformFilesxq.vue";
import {getStatusText} from '@/utils/index'

export default {
  components: {
    //BudgettableJson,
    PlatformFiles,
    PlatformFilesxq,
    platformFiles,
    Budget,
    Dialog,
    ColumnData,
    PopupTreeInput,
    UserListModal,
    Export,
  },
  props: {
    initData: {
      type: Object,
      required: true,
    },
    initNum: {
      type: Object,
      required: true,
    },
  },
  setup(props, { emit }) {
    let selectedRows: ObjectType[] = [];
    //列表显示的字段
    //模态框以及信息栏是否显示
    let data = reactive({
      allTableData: [],
      tableItem: { id: '',type:'',status:'' },//当前选中的行
      popupTreeProps: {
        label: "name",
        children: "children",
      },
      dialogType: 'look',//编辑或回显
      selectArr: [],
      checkId: "",
      examinationVisible: false,
      page: 1,
      pageSize: 10,
      total: 0,
      detailForm: {
        reporttime: null,
      },
      detail: {
        telephone: '',
        projectname: '',
        projectleaderid: '',
      } as any,
      detailVisible: false,
      columns: tableData.lxsqTableHeader,
      time: [],
      initData: {},
      persionDialogVisible: false, //  选择参与人员弹框
      ruleForm: {
        type: 5,
        applicationunit: "",
        projectleader: "",
      } as any,
      files: [],
      dialogVisible: false,
      orgAllList: [],
      exportDialog: false,
      detailList: [] as any,
      allTableloading: false,
      statusUpdate:"",//状态判断
      tableJson:[],
      approvalFormalExamination: {
        modifyUsername: '',
        comment: '',
        reviewtime: '',
        status: '',
        files: []
      }
    });
    const closeExport = () => {
      data.exportDialog = false
    }
    const  close = ()=>{
      ruleFormRef.value.resetFields()
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      let sdt = selectArr.map((el) => el.id);
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          // exportProjectList({ ...searchParams, ids: sdt.join(",") , headList: arr }, '科研项目数据表格')
          getExportApply({ ...searchParams, ids: [data.tableItem.id] , headList: arr}, "科研项目工作大纲审查");
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectname', title: '项目名称' },
        { fieldName: 'applicationunit', title: '申请单位' },
        { fieldName: 'projectleader', title: '项目负责人' },
        { fieldName: 'telephone', title: '联系电话' },
        { fieldName: 'completionperiod', title: '完成年限' },
        { fieldName: 'totalinvestment', title: '总投资(万元)' },
        { fieldName: 'applyfunding', title: '申请中咨拨款（万元）' },
        { fieldName: 'reporttime1', title: '申报日期' },
        { fieldName: 'researchcontents', title: '主要研究内容' },
        { fieldName: 'mainindicators', title: '主要技术经济指标' },
        { fieldName: 'describetwo', title: '创新点及可能获得的成果和知识产权' },
        { fieldName: 'backdrop', title: '立项背景' },
        { fieldName: 'analysis', title: '国内外研究概况及可行性分析' },
        { fieldName: 'qualification', title: '项目研究的主要内容及技术指标' },
        { fieldName: 'roadmap', title: '项目研究的技术路线' },
        { fieldName: 'forecast', title: '推广应用前景及经济效益预测' },
        { fieldName: 'dividethework', title: '申报单位和协作单位及分工' },
        { fieldName: 'programme', title: '项目进度计划' },
      ]
    }
    interface Config {
      id: string;
      type: string;
      status: string;
    }
    let selectArr: Config[] = reactive([]);
    const handleSelectionChange = (val) => {
      selectArr = val;
    };

    const deptForm = {
      parentId: 0,
      parentName: "",
    };


    let loading = ref(true);
    // 查询参数
    let searchParams = reactive({
      type: 5,
      typeParams: 1,
      startTime: null,
      endTime: null,
    }) as any;
    //单选
    const selectTable = (e, row, index) => {

      const data1 = data.allTableData

      //遍历表格的数据，将非本行的所有数据的checked属性置为false，即取消选择
      for (let i in data1) {
        if (i == index) {
          (data1[i] as any).checked = e
        } else {
          (data1[i] as any).checked = false
        }
      }
      data.allTableData = data1
      if (e) {
        data.tableItem = row
      } else {
        data.tableItem = { id: '', type: '', status: '', }
      }

    }
    const options: any = reactive({
      yearList: [
        { itemName: "2026年", itemValue: 2026 },
        { itemName: "2025年", itemValue: 2025 },
        { itemName: "2024年", itemValue: 2024 },
        { itemName: "2022年", itemValue: 2022 },
        { itemName: "2021年", itemValue: 2021 },
        { itemName: "2020年", itemValue: 2020 },
        { itemName: "2019年", itemValue: 2019 },

      ],
      statusDate: [
        { itemName: "全部", itemValue: "10" },
        { itemName: "待审查", itemValue: "1" },
        // { itemName: "审查通过", itemValue: "2" },
        { itemName: "审批不通过", itemValue: "3" },
        { itemName: "已上报", itemValue: "4" },
        { itemName: "退回", itemValue: "5" },
        { itemName: "领导班子会审中", itemValue: "8" },
        { itemName: "已批准立项", itemValue: "9" },
      ],
      unitnameList: [],
      affiliationList: [],
      SoftnessList: [],
      classnameList: [],
      competitionclassList: [],
      belongingunitList: [],
      awardList: [],
      zlztList: [],
      jsflList: [],
      xmlbList: [],
      yhrenList: [],
    });
    // 判断
    const rules = reactive({
      projectname: [{ required: true, message: "请输入项目名称", trigger: "blur" }],

      applicationunit: [{ required: true, message: "请选择申报单位", trigger: "change" }],

      projectleaderid: [
        { required: true, message: "请选择项目负责人", trigger: "change" },
      ],

      telephone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],

      completionperiod: [
        { required: true, message: "请选择完成年限", trigger: "change" },
      ],

      totalinvestment: [
        { required: true, message: "请输入总投资(万元)", trigger: "change" },
      ],

      applyfunding: [
        { required: true, message: "申请中咨拨款(万元)", trigger: "change" },
      ],

      reporttime: [{ required: true, message: "请选择申报日期", trigger: "change" }],
      status: [{ required: true, message: "请选择状态", trigger: "change" }],
    });
    const changeDialog = () => {
      data.tableItem.id = '';
      getListData()
      data.examinationVisible = false;
    };
    // 清除日期选择器,删除的时候将日期清空
    const dataPickerChange = () => {
      if (data.time) {
        searchParams.startTime = data.time[0];
        searchParams.endTime = data.time[1];
      } else {
        searchParams.startTime = null;
        searchParams.endTime = null;
        data.time = [];
      }
    };

    const pageChange = (current) => {
      data.page = current;
      getListData();
    };
    const getListData = async () => {
      data.selectArr = [];
      loading.value = true;
      data.allTableloading = true;
      if(data.statusUpdate == "1"){
        searchParams.type=5;
        searchParams.status=1;
        searchParams.typeParams=0;
      } else if (data.statusUpdate =="2"){
        searchParams.type=5;
        searchParams.status=2;
        searchParams.typeParams=0;
      } else if (data.statusUpdate =="3"){
        searchParams.type=5;
        searchParams.status=3;
        searchParams.typeParams=3;
      }else if (data.statusUpdate =="4"){
        searchParams.type=5;
        searchParams.status=4;
        searchParams.typeParams=0;
      }else if (data.statusUpdate =="5"){
        searchParams.type=5;
        searchParams.status=5;
        searchParams.typeParams=0;
      }else if (data.statusUpdate =="8"){
        searchParams.type=6;
        searchParams.status=1;
        searchParams.typeParams=0;

      } else if (data.statusUpdate =="9"){
        searchParams.type=7;
        searchParams.status=2;
        searchParams.typeParams=0;

      } else if (data.statusUpdate =="10"){
        searchParams.type=5;
        searchParams.typeParams=1;
        delete searchParams.status;


      }

      return request({
        url: proxy.CHECC_API_CMS + "/xmzx/kyxmlxps/approvalApplication/getTotalList",
        method: "post",
        data: {
          ...searchParams,
          page: data.page,
          pageSize: data.pageSize,
        },
      })
        .then((res) => {
          let resData = res.data.data.records;
          //草稿、待审批、审批通过、审批拒绝
          resData.map((item: any) => {
            if (item.status == 1 && item.type == 5) {
              item.status = "待审查";
            } else if (item.status == 2 && item.type == 5) {
              item.status = "审批通过";
            } else if (item.status == 3 && item.type == 5) {
              item.status = "审批不通过";
            } else if (item.status == 4 && item.type == 5) {
              item.status = "已上报";
            } else if (item.status == 5 && item.type == 5) {
              item.status = "退回";
            } else if (item.status == 1 && item.type == 6) {
              item.status = "领导班子会审中";
            } else if (item.status == 3 && item.type == 6) {
              item.status = "领导班子会审不通过";
            } else if (item.status == 1 && item.type == 7) {
              item.status = "批准立项中";
            } else if (item.status == 2 && item.type == 7) {
              item.status = "已批准立项";
            } else if (item.status == 3 && item.type == 7) {
              item.status = "批准立项不通过";
            }
            if (item) {
              item.reporttimeFormat = moment(item.reporttime).format("YYYY-MM-DD");
            }


          });

          //给数据添加checked属性并默认置为false
          for (let index in res.data.data.records) {

            res.data.data.records[index].checked = false
          }

          data.allTableData = res.data.data.records;
          data.total = res.data.data.total;
          data.allTableloading = false;

        })
        .finally(() => {
          loading.value = false;
          data.allTableloading = false;

        });
    };
    getListData();
    const ruleFormRef = ref();
    // 保存按钮
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid) => {
        console.log(valid,'ruleFormRef.value')
        if (valid) {
          if (!validatePhoneNumber(data.detail.telephone)) {
            tips("联系电话格式不正确！", "warning");
            return false;
          }
          data.detail.status = 4
          const config: Record<string, any> = {
            info: {
              ...data.detail,
            },
            // contractBudgetList: data.tableJson,
          };
          loading.value = true;
          return request({
            url:
              proxy.CHECC_API_CMS +
              `/xmzx/kyxmlxps/approvalApplication/${editId ? "update" : "insert"}`,
            method: "post",
            data: config,
          }).then(() => {
            getListData();
            // data.dialogVisible = false;
            data.detailVisible = false
            return ElMessage({
              message: "操作成功",
              type: "success",
            });
          });
        } else {
          return ElMessage({
            message: "请将基本信息补充完整",
            type: "warning",
          });
        }
      });
    };
    //形式审查
    const handleExamina = () => {

      if (!data.tableItem.id) {

        ElMessage({
          message: "请选择",
          type: "warning",
        });
        return false
      }
      if (data.tableItem.type !='5') {

        ElMessage({
          message: "请选择处于工作大纲审查的数据",
          type: "warning",
        });
        return false
      }
      if(data.tableItem.status == "待审查" ||data.tableItem.status == "已上报" ){
        data.examinationVisible = true;
      }else {
        ElMessage({
          message: "请选择处于待审查的数据",
          type: "warning",
        });
        return false
      }


    };
    //主页面表格初始化
    //新增

    const handleClose = () => {
      for (let key in data.ruleForm) {
        data.ruleForm[key] = "";
      }
      activeName.value = "first";
    };
    const handleEditItem = (row) => {
      row.isEdit = true;
    };
    const cancelItem = (row) => {
      row.isEdit = false;
    };

    //编辑按钮
    let editId = "";
    const handleEdit = async (row) => {
      // data.tableJson = [];

      editId = row.id;

      let res = await getDetailById(row.id);

      if (res.data.success) {
        data.ruleForm = { ...res.data.data.info };
        // data.tableJson = res.data.data.contractBudgetList;
        // console.log("编辑按钮", data.tableJson);
      }
      // data.addFlag = 1;
      data.dialogVisible = true;
    };

    const ruleForm = reactive({});
    const handleRowClick = (row) => {
      handleDetail(row,'look')
    }
    const indexMethod = (index)=>{
      return data.pageSize*(data.page-1) +index+1
    }
    //打开弹窗
    let handleDetail = async (row, type) => {
      activeName.value = "first";
      data.dialogType = type
      editId = row.id;
      data.allTableloading = true;
      getApprovalById(row.id).then(arew => {
        if(arew.data.success) {
          let item = arew.data.data.approvalFormalExamination
          if(item) {
            let file = item.examinationurl ? JSON.parse(item.examinationurl) : []
            item.reviewtime = moment(item.reviewtime).format('YYYY-MM-DD hh:mm:ss')
            item.files = file
            
            if(item.status === 5  && item.type === '1') {
                data.approvalFormalExamination = {
                modifyUsername: '',
                comment: '',
                reviewtime: '',
                status: '',
                files: []
              }
            } else {
              data.approvalFormalExamination = item
              data.approvalFormalExamination.status = getStatusText([Number(item.status), Number(item.type)])
            }
          } else {
            data.approvalFormalExamination = {
              modifyUsername: '',
              comment: '',
              reviewtime: '',
              status: '',
              files: []
            }
          }
      
        }
      })
      let res = await getDetailById(row.id)
      
      activeName.value = "first";
      data.allTableloading = false;
      if (res.data.success) {

        data.detail = res.data.data.info
        data.tableJson = res.data.data.contractBudgetList
        data.files= res.data.data.files
        data.detailVisible = true;
      }
    
     
    };


    // const handleSelectionChange = () => {
    //
    //
    // }

    const getExport = async () => {
      Modals('是否导出全部数据', '提示', 'warning').then(async () => {
        await getExportApply(searchParams, '工作大纲审查')
      }).catch(() => {
        console.log("点击了取消")
      })
    };
    //page分页
    let getpageData = () => {
      data.selectArr = [];
      getListData();
    };
    //承载单位
    const czdw = () => {
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res => {
        data.orgAllList = res.data.data
      })
    };
    onMounted(() => {
      czdw();
    });

    const activeName = ref("first");

    const changeUnit = (item) => {
      data.detail.applicationunit = item.name;
      data.detail.applicationunitid = item.id;
    };
    const changeProject = (val) => {
      data.detail.projectleader = val.cname;
      data.detail.projectleaderid = val.userId;
    };
    let filesParams = (params) => {
      data.files = params;
    };

    // 预算
    let changeBudget = (parmas) => {
      data.tableJson = parmas.contractBudgetList
    }
    return {
      changeProject,
      changeUnit,
      data,
      dataPickerChange,
      selectTable,
      handleExamina, // 审核
      handleClose,
      handleDetail, //确认
      getListData, // 获取列表信息
      getpageData, // 分页信息
      handleEdit, //编辑
      handleEditItem,
      pageChange,
      getExport,
      options, //维护单位字典
      selectedRows,
      searchParams,
      activeName,
      handleSelectionChange,
      changeDialog,
      cancelItem,
      rules,
      deptForm,
      submitForm,
      ruleFormRef,
      closeExport,
      handleFiled,
      close,
      handleExport,
      handleRowClick,
      indexMethod,
      filesParams,
      changeBudget,
    };
  },
};
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}

.el-col {
  line-height: 40px;
}


:deep(.center-table td),
:deep(.center-table th) {
  text-align: center !important;
}

:deep(.center-table) {
  margin-top: 15px;
}

.el-form-item {
  .el-input {
    width: 100px;
    background-color: aliceblue;
  }

  .el-select {
    width: 100px;
  }
}

.custom-color {
  color: red !important;
  /* 确保优先级高于其他样式 */
}

.el-table th {
  background-color: #f0f0f0;
  /* 修改表头背景色 */
  color: #333;
  /* 修改表头文字颜色 */
}

.demo-tabs>.el-tabs__content {
  padding: 320px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.open-title {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
}

/deep/ .el-dialog__body {
  display: block !important;
}

.mt15 {
  margin-top: 15px;
}

.mb10 {
  margin-bottom: 10px;
}

:deep(.demo-tabs > .el-tabs__content) {
  max-height: 500px;

  overflow-y: scroll;

  scrollbar-width: none;

  -ms-overflow-style: none;
}

:deep(.el-dialog__header) {
  display: none;
}

.tc {
  text-align: center;
}

.info {
  display: flex;
}

thead .el-table-column--selection .cell {
  display: none !important;
}
.inline-form::v-deep {
  .el-form-item {
    display: flex;
  }
  .el-form-item__label {
    width: 120px;
    text-align: right;
  }
  .el-form-item__content {
    opacity: .8;
  }
}
</style>
